from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from tools.myLogger import logger

class BasePage():

    def __init__(self, driver):
        logger.info("实例化浏览器对象，开始运行测试用例。")
        # 实例化浏览器对象
        # self.driver = webdriver.Chrome("C:\Program Files\driver\chromedriver.exe")
        self.driver = driver
        # 设置隐式等待
        self.driver.implicitly_wait(10)

    def get_url(self, url):
        logger.info("打开页面，页面地址：{}".format(url))
        self.driver.get(url)

    def my_find_element(self, ele, timeout=20, poll_frequency=0.5):
        # self.ele = self.driver.find_element(*ele)
        # 显式等待,查找元素
        logger.info("定位元素，元素表达式：{}".format(ele))
        try:
            self.ele = WebDriverWait(self.driver, timeout, poll_frequency).until(EC.presence_of_element_located(ele))
            logger.info("元素定位成功！")
        except:
            logger.error("元素定位失败，无法继续操作。")
            raise Exception


    def my_click(self, ele, **kwargs):
        self.my_find_element(ele, **kwargs)
        logger.info("点击元素")
        self.ele.click()

    def my_send_keys(self, ele, word, **kwargs):
        self.my_find_element(ele, **kwargs)
        logger.info("元素内输入值：{}".format(word))
        self.ele.send_keys(word)

    def my_quit(self):
        logger.info("关闭浏览器！")
        self.driver.quit()

    def my_get_cookies(self):
        return self.driver.get_cookies()

    def get_text(self, ele):
        """
        获取元素的文本值
        :param ele:
        :return:
        """
        self.my_find_element(ele)
        return self.ele.text

    def clear_input(self, ele):
        """
        清空输入框
        :return:
        """
        self.my_find_element(ele)
        self.ele.clear()

